package org.spbsu.timetable.model;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.spbsu.timetable.utils.Evaluator;

public class Timetable {
	private static final Logger LOG = Logger.getLogger(Timetable.class);

	private Lesson[][] lessons;

	// private Integer daysLimit;
	// private Map<Integer, Day> days = new HashMap<>();
	//
	public Timetable(Integer daysPerWeek, Integer pairsPerDay) {
		lessons = new Lesson[daysPerWeek][pairsPerDay];

		for (Lesson[] row : lessons) {
			Arrays.fill(row, Lesson.getEmpty());
		}

		// Arrays.fill(arg0, arg1)
	}

	//
	// public Day addDay(Day day, Integer position) {
	// if (position < 0 || position >= daysLimit) {
	// LOG.error("Position " + position + " is invalid.");
	//
	// return null;
	// }
	//
	// if (days.get(position) != null) {
	// LOG.error("Position " + position + " has been already occupated.");
	//
	// return null;
	// }
	//
	// days.put(position, day);
	// return days.get(position);
	// }
	//
	// public Integer getDaysLimit() {
	// return daysLimit;
	// }
	//
	// public void setDaysLimit(Integer daysLimit) {
	// this.daysLimit = daysLimit;
	// }
	//
	@Override
	public String toString() {
		String buffer = "";

		for (int i = 0; i < lessons.length; ++i) {
			buffer += "Day" + i + ": ";
			for (int j = 0; j < lessons[i].length; ++j) {
				buffer += lessons[i][j] + " ";
			}
			buffer += "\n";
		}

		return buffer;
	}
	
	public Integer getDaysQnt() {
		return lessons.length;
	}
	
	public Integer getLessonsQnt() {
		if (lessons.length == 0) {
			return 0;
		}
		return lessons[0].length;
	}

	public Lesson addPair(Lesson lesson) {
		Map<Pair<Integer, Integer>, Double> ratings = new HashMap<>();

		for (int i = 0; i < lessons.length; ++i) {
			for (int j = 0; j < lessons[i].length; ++j) {
				if (lessons[i][j].equals(Lesson.getEmpty())) {
					Pair<Integer, Integer> position = new Pair<>(i, j); 
					ratings.put(position,
							Evaluator.evaluate(lesson, position, this));
				}
			}
		}

		Pair<Integer, Integer> bestPair = new Pair<Integer, Integer>(
				Integer.MIN_VALUE, Integer.MIN_VALUE);
		Double bestRating = Double.MIN_VALUE;

		for (Pair<Integer, Integer> pair : ratings.keySet()) {
			if (ratings.get(pair) > bestRating) {
				bestRating = ratings.get(pair);
				bestPair = pair;
			}
		}

		try {
			lessons[bestPair.getFirst()][bestPair.getSecond()] = lesson;
			LOG.info("Lesson " + lesson + " has been added to " + bestPair + ".");
		} catch (Exception e) {
			LOG.info("Can not add lesson " + lesson + " to " + bestPair + ".");
		}

		return Lesson.getEmpty();
	}
}
